package cn.edu.sgu.www.mhxysy.util;

import cn.edu.sgu.www.mhxysy.config.property.UploadsProperties;
import cn.edu.sgu.www.mhxysy.exception.GlobalException;
import cn.edu.sgu.www.mhxysy.restful.ResponseCode;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 文件上传工具类
 * @author heyunlin
 * @version 1.0
 */
@Component
public class UploadUtils {

    /**
     * 文件上传根路径
     */
    private final String root;

    /**
     * 图片文件名后缀
     */
    private final List<String> picSuffix;

    /**
     * 小写字母
     */
    private static final String LOWER_LETTERS = "abcdefghijklmnopqrstuvwxyz";

    public UploadUtils(UploadsProperties uploadsProperties) {
        root = uploadsProperties.getPath();
        picSuffix = uploadsProperties.getFileTypes();
    }

    public String getRoot() {
        return root;
    }

    /**
     * 图片上传
     * @param file MultipartFile对象
     * @param directory 文件上传目录
     * @return String 图片的相对路径
     */
    public String upload(MultipartFile file, String directory) throws IOException {
        boolean result = check(file);

        if (result) {
            // 得到请求参数中的数据ID
            String id = HttpUtils.getRequest().getParameter("id");

            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            assert originalFilename != null;
            String fileName = getBase(directory.charAt(1) + "") + Integer.parseInt(id)
                    + StringUtils.getFileType(originalFilename);
            // 创建目标对象
            File targetFile = new File(root + directory, fileName);

            // 保存文件
            file.transferTo(targetFile);

            return directory + "/" + fileName;
        }

        return null;
    }

    /**
     * 检查文件格式
     * @param file MultipartFile
     */
    private boolean check(MultipartFile file) {
        if (file == null) {
            throw new GlobalException(ResponseCode.BAD_REQUEST, "您未上传任何图片！");
        }

        String filename = file.getOriginalFilename();

        if (StringUtils.isNotEmpty(filename)) {
            String fileType = StringUtils.getFileType(filename);

            if (!picSuffix.contains(fileType)) {
                throw new GlobalException(ResponseCode.BAD_REQUEST, "只允许上传格式为" + picSuffix + "的图片");
            }

            return true;
        } else {
            throw new GlobalException(ResponseCode.BAD_REQUEST, "获取上传的文件名失败~");
        }
    }

    public int getBase(String tableName) {
        // 得到表名的首字母
        int base = LOWER_LETTERS.indexOf(tableName.toLowerCase().charAt(0));

        base ++; // 数组下标从0开始
        base %= 10;
        base *= 1000;

        return base;
    }

}